using Joy.Erp.BasicArchives.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.DependencyInjection;
using Volo.Abp.EntityFrameworkCore.Modeling;

namespace Joy.Erp.BasicArchives.ItemMasters
{
    public class BomMasterModelConfiguration : IModelConfiguration
    {
        public void Build(ModelBuilder builder)
        {
            builder.Entity<BomMaster>(b =>
            {
                b.ToTable(BasicArchivesDbProperties.DbTablePrefix + nameof(BomMaster), BasicArchivesDbProperties.DbSchema);
                b.ConfigureByConvention();
                b.ConfigureDocumentAggregateRoot<BomMaster, BomComponent>();

                b.Property(x => x.Version).HasMaxLength(BomMasterConsts.VersionMaxLength);
                b.Property(x => x.ItemMasterId).IsRequired();
                b.Property(x => x.ItemCode).IsRequired(BomMasterConsts.ItemCodeRequired);
                b.Property(x => x.ItemCode).HasMaxLength(BomMasterConsts.ItemCodeMaxLength);
                b.Property(x => x.ItemName).HasMaxLength(BomMasterConsts.ItemNameMaxLength);
                b.Property(x => x.ItemSpec).HasMaxLength(BomMasterConsts.ItemSpecMaxLength);
                b.Property(x => x.UseCount).HasColumnType(BomMasterConsts.UseCountColumnType);
                b.Property(x => x.ParentCount).HasColumnType(BomMasterConsts.ParentCountColumnType);
                b.Property(x => x.UnitId).IsRequired();

                b.HasOne(x => x.ItemMaster).WithMany().HasForeignKey(x => x.ItemMasterId).OnDelete(DeleteBehavior.Restrict);
                b.HasOne(x => x.Unit).WithMany().HasForeignKey(x => x.UnitId).OnDelete(DeleteBehavior.Restrict);

                b.HasMany(x => x.Children).WithOne(x => x.Document).HasForeignKey(x => x.DocumentId).OnDelete(DeleteBehavior.Cascade);
            });
        }

        public void Entity(IAbpDbContextRegistrationOptionsBuilder options)
        {
            options.Entity<BomMaster>(opt =>
            {
                opt.DefaultWithDetailsFunc = query =>
                {
                    return query
                        .Include(x => x.ItemMaster)
                        .Include(x => x.Unit)
                        .Include(x => x.Children)
                            .ThenInclude(x => x.ItemMaster)
                        .Include(x => x.Children)
                            .ThenInclude(x => x.Unit)
                        ;
                };
            });
        }
    }
}